#ifndef Foundation_RecursiveDirectoryIteratorImpl_INCLUDED
#define Foundation_RecursiveDirectoryIteratorImpl_INCLUDED

#include <fermat/common/directory_iterator_strategy.h>
#include <stack>
#include <functional>

namespace fermat {


class ChildrenFirstTraverse;
class SiblingsFirstTraverse;


template<class TTraverseStrategy = ChildrenFirstTraverse>
class RecursiveDirectoryIteratorImpl {
public:
	enum
	{
		D_INFINITE = 0 /// Special value for infinite traverse depth.
	};

	RecursiveDirectoryIteratorImpl(const std::string& path, uint16_t maxTraversalDepth = D_INFINITE)
		: _maxDepth(maxTraversalDepth), _traverseStrategy(std::ptr_fun(depthFun), _maxDepth), _isFinished(false), _rc(1)
	{
		_itStack.push(DirectoryIterator(path));
		_current = _itStack.top()->path();
	}

	~RecursiveDirectoryIteratorImpl()
	{
	}

	inline void duplicate()
	{
		++_rc;
	}

	inline void release()
	{
		if (--_rc == 0)
			delete this;
	}

	inline uint16_t depth() const
	{
		return depthFun(_itStack);
	}

	inline uint16_t maxDepth() const
	{
		return _maxDepth;
	}

	inline const std::string& get() const
	{
		return _current;
	}
	const std::string& next()
	{
		if (_isFinished)
			return _current;

		_current = _traverseStrategy.next(&_itStack, &_isFinished);

		return _current;
	}

private:
	typedef std::stack<DirectoryIterator> Stack;

	/// Function which implements the logic of determining
	/// recursion depth.
	static uint16_t depthFun(const Stack& stack)
	{
		return static_cast<uint16_t>(stack.size());
	}

	uint16_t           _maxDepth;
	TTraverseStrategy  _traverseStrategy;
	bool               _isFinished;
	Stack              _itStack;
	std::string        _current;
	int                _rc;
};


} 


#endif 
